<?php
// 引入数据库配置
require 'config.php';
// 引入发送邮件函数
require 'send_email.php';

// 设置响应头为JSON格式
header('Content-Type: application/json');

// 添加调试日志
error_log("Request received at: " . date('Y-m-d H:i:s'));
error_log("Request method: " . $_SERVER['REQUEST_METHOD']);
error_log("Content type: " . $_SERVER['CONTENT_TYPE'] ?? 'Not set');

// 检查请求方法是否为POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
    echo json_encode(['success' => false, 'message' => '请求方法错误，只支持POST请求']);
    exit;
}

// 检查是否是图片上传请求
if (isset($_POST['ticket_id']) && !empty($_FILES['screenshots']['name'][0])) {
    // 这里是图片上传逻辑，稍后会移动到专门的文件
    echo json_encode(['success' => false, 'message' => '请使用upload_image.php接口上传图片']);
    exit;
}

// 获取表单数据
$qqNumber = $_POST['qqNumber'] ?? '';
$feedbackType = $_POST['feedbackType'] ?? '';
$severity = $_POST['severity'] ?? '';
$description = $_POST['description'] ?? '';

error_log("Form data received: qqNumber=$qqNumber, feedbackType=$feedbackType, severity=$severity");

// 验证表单数据
$errors = [];

if (empty($qqNumber) || !preg_match('/^[1-9][0-9]{4,10}$/', $qqNumber)) {
    $errors[] = '请输入有效的QQ号码（5-11位数字，不能以0开头）';
}

if (empty($feedbackType)) {
    $errors[] = '请选择反馈类型';
}

if (empty($severity) || !in_array($severity, ['1', '2', '3', '4', '5'])) {
    $errors[] = '请选择问题严重程度';
}

if (empty($description)) {
    $errors[] = '请描述您遇到的问题';
} elseif (strlen($description) > 2000) {
    $errors[] = '问题描述不能超过2000个字符';
}

// 如果有错误，返回错误信息
if (!empty($errors)) {
    // 调试信息：记录错误信息
    error_log("Errors: " . print_r($errors, true));
    echo json_encode(['success' => false, 'message' => $errors]);
    exit;
}

// 将工单数据插入数据库
// 调试信息：记录要插入的数据
error_log("Inserting data: qq_number=$qqNumber, feedback_type=$feedbackType, severity=$severity");

try {
    $sql = "INSERT INTO tickets (qq_number, feedback_type, severity, description, created_at)
            VALUES (:qq_number, :feedback_type, :severity, :description, NOW())";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':qq_number', $qqNumber);
    $stmt->bindParam(':feedback_type', $feedbackType);
    $stmt->bindParam(':severity', $severity, PDO::PARAM_INT);
    $stmt->bindParam(':description', $description);
    
    $stmt->execute();
    
    // 获取插入的工单ID
    $ticketId = $pdo->lastInsertId();

    // 调试信息：记录插入成功
error_log("Ticket inserted successfully with ID: $ticketId");

    // 检查是否需要发送新工单通知
    try {
        $sql = "SELECT notification_enabled, notification_email FROM smtp_settings WHERE id = 1";
        $stmt = $pdo->query($sql);
        $settings = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($settings && $settings['notification_enabled'] && !empty($settings['notification_email'])) {
            // 发送新工单通知
            $subject = "新工单通知 #$ticketId";
            // 动态获取当前域名
            $protocol = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http';
            $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost:8000';
            $base_url = $protocol . '://' . $domain;
            
            // 反馈类型映射为中文
            $typeMap = [
                'account' => '账号问题',
                'function' => '功能故障',
                'suggestion' => '功能建议',
                'performance' => '性能问题',
                'security' => '安全问题',
                'other' => '其他问题'
            ];
            $chineseFeedbackType = $typeMap[$feedbackType] ?? $feedbackType;

            $message = "<p>收到新工单：</p>"
                     . "<p><strong>工单ID：</strong> $ticketId</p>"
                     . "<p><strong>QQ号码：</strong> $qqNumber</p>"
                     . "<p><strong>反馈类型：</strong> $chineseFeedbackType</p>"
                     . "<p><strong>严重程度：</strong> $severity</p>"
                     . "<p><strong>问题描述：</strong> $description</p>"
                     . "<p>请登录后台查看详情：<a href='$base_url/admin/view_ticket.php?id=$ticketId'>查看工单</a></p>";

            // 正确调用send_email函数，参数顺序为：收件人邮箱、收件人姓名、主题、邮件内容
            $success = send_email($settings['notification_email'], '管理员', $subject, $message);
            if ($success) {
                error_log("通知邮件发送成功到: " . $settings['notification_email']);
            } else {
                error_log("通知邮件发送失败到: " . $settings['notification_email']);
            }
        }
    } catch(PDOException $e) {
        error_log("查询SMTP设置失败: " . $e->getMessage());
    }

    echo json_encode([
        'success' => true, 
        'message' => '工单基本信息提交成功，请上传图片', 
        'ticket_id' => $ticketId
    ]);
} catch(PDOException $e) {
    // 调试信息：记录数据库错误
error_log("Database error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => '数据库错误，请稍后再试']);
}
?>